package com.secondhand.project.service.impl;

import cn.hutool.core.date.DateUtil;
import com.secondhand.common.utils.SecurityUtils;
import com.secondhand.project.domain.Collect;
import com.secondhand.project.domain.Goods;
import com.secondhand.project.domain.Likes;
import com.secondhand.project.mapper.CollectMapper;
import com.secondhand.project.mapper.GoodsMapper;
import com.secondhand.project.mapper.LikesMapper;
import com.secondhand.project.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements IGoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private LikesMapper likesMapper;
    @Autowired
    private CollectMapper collectMapper;

    private Goods wrap(Goods g) {
        Likes likes = new Likes();
        likes.setFid(g.getId());
        likes.setUserId(SecurityUtils.getUserId());
        List<Likes> likesList = likesMapper.selectLikesList(likes);
        if (!likesList.isEmpty()) {
            g.setLiked(true);
        }

        Collect collect = new Collect();
        collect.setFid(g.getId());
        collect.setUserId(SecurityUtils.getUserId());
        List<Collect> collectList = collectMapper.selectCollectList(collect);
        if (!collectList.isEmpty()) {
            g.setCollected(true);
        }
        return g;
    }

    @Override
    public Goods selectGoodsById(Long id) {
        return wrap(goodsMapper.selectGoodsById(id));
    }

    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        Long userId = SecurityUtils.getUserId();

        if (!SecurityUtils.isAdmin(userId)) {//不是管理员
            goods.setUserId(userId);
            return goodsMapper.selectGoodsListByRole(goods);
        } else {
            return goodsMapper.selectGoodsList(goods);
        }
    }

    @Override
    public int insertGoods(Goods goods) {
        goods.setUserId(SecurityUtils.getUserId());
        goods.setDate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
        return goodsMapper.insertGoods(goods);
    }

    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateGoods(goods);
    }

    @Override
    public int deleteGoodsByIds(Long[] ids) {
        return goodsMapper.deleteGoodsByIds(ids);
    }

    @Override
    public int deleteGoodsById(Long id) {
        return goodsMapper.deleteGoodsById(id);
    }
}
